package cn.wowjoy.office.materialinspection.applyfor.produce;

import android.app.Instrumentation;
import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.PopupWindow;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseActivity;
import cn.wowjoy.office.common.decoration.SimpleItemDecoration;
import cn.wowjoy.office.common.widget.AlphaManager;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.common.widget.timepicker.BottomMenuPopupStock;
import cn.wowjoy.office.data.constant.Constants;
import cn.wowjoy.office.data.request.GoodStockRequest;
import cn.wowjoy.office.data.response.ApplyDemandHeadDetailItem;
import cn.wowjoy.office.data.response.StockApplyDemandHeadDetailResponse;
import cn.wowjoy.office.data.response.StockStorageResponse;
import cn.wowjoy.office.databinding.ActivityStockApplyProduceBinding;
import cn.wowjoy.office.materialinspection.Thread.ThreadManager;
import cn.wowjoy.office.materialinspection.stockout.otherout.detail.StockOutDetailActivity;
import cn.wowjoy.office.materialinspection.stockout.otherout.edit.StockOutHandEditActivity;
import cn.wowjoy.office.utils.ToastUtil;

public class StockApplyProduceActivity extends NewBaseActivity<ActivityStockApplyProduceBinding,StockApplyProduceViewModel> implements View.OnClickListener {


    private StockApplyDemandHeadDetailResponse mResponse;
    private int notifyPosition;
    private MDialog waitDialog;
   private LinearLayoutManager mLinearLayoutManager;
    private String permission;
    private BottomMenuPopupStock mMenuPop1;
    private boolean isHasFlid = false;
    private MDialog mDialog;

    @Override
    protected Class<StockApplyProduceViewModel> getViewModel() {
        return StockApplyProduceViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_stock_apply_produce;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
      binding.setViewModel(viewModel);

       mLinearLayoutManager = new LinearLayoutManager(this);
        binding.recyclerView.setLayoutManager(mLinearLayoutManager);
        binding.recyclerView.setEmptyView(binding.emptyView.getRoot());
        binding.recyclerView.setAdapter(viewModel.adapter);
        viewModel.adapter.removeFooterView();
        viewModel.adapter.removeHeaderView();
        binding.recyclerView.addItemDecoration(new SimpleItemDecoration(this, SimpleItemDecoration.VERTICAL_LIST));
        binding.recyclerView.setPullRefreshEnabled(false);
        binding.recyclerView.setPullRefreshEnabled(false);
        binding.emptyView.emptyContent.setText("空空的物资列表");
        binding.appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset < 0){
                    isHasFlid = true;
                } else {
                    isHasFlid = false;
                }
            }
        });
        binding.back.setOnClickListener(this);
        binding.tvSubmitOtherStock.setOnClickListener(this);

      binding.closeNotice.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              binding.noticeRl.setVisibility(View.GONE);
          }
      });
       viewModel.applyPermission();
       initObserve();

    }

    @Override
    protected void onResume() {
        super.onResume();
        openBroadCast();
      //  mResponse = (StockApplyDemandHeadDetailResponse) getIntent().getSerializableExtra("model");
        String storageView = getIntent().getStringExtra("storageView");
        String commitDeptView = getIntent().getStringExtra("commitDeptView");
        Log.e("PXY", "storageView: "+ storageView +",   commitDeptView"+commitDeptView);
        binding.tvTypeOutdetail.setText(storageView);
        binding.tvKeshi.setText(commitDeptView);
        try {
            viewModel.mApplyDemandHeadDetailItems = (List<ApplyDemandHeadDetailItem>) getIntent().getSerializableExtra("selectList");
            viewModel.mOtherOutLrAdapter.setDates(viewModel.mApplyDemandHeadDetailItems);
        }catch (Exception e){
            e.printStackTrace();
        }

//        viewModel.mApplyDemandHeadDetailItems = mResponse.getList();
//        viewModel.mOtherOutLrAdapter.setDates(mResponse.getList());
    }

    private void initObserve() {
        viewModel.getScanData().observe(this, new Observer<LiveDataWrapper<ApplyDemandHeadDetailItem>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<ApplyDemandHeadDetailItem> ApplyDemandHeadDetailItemLiveDataWrapper) {
                switch (ApplyDemandHeadDetailItemLiveDataWrapper.status) {
                    case LOADING:
                        waitDialog = CreateDialog.waitingDialog(StockApplyProduceActivity.this);
                        break;
                    case SUCCESS:
                        if (null != waitDialog) {
                            CreateDialog.dismiss(StockApplyProduceActivity.this, waitDialog);
                        }
                        if (null != ApplyDemandHeadDetailItemLiveDataWrapper.data) {
                            Log.e("PXY", "onChanged: "+ ApplyDemandHeadDetailItemLiveDataWrapper.data.toString());
                            viewModel.updateFactOut(ApplyDemandHeadDetailItemLiveDataWrapper.data, StockApplyProduceActivity.this, mLinearLayoutManager, binding.recyclerView);
                        }
                        break;
                    case ERROR:
                        if (null != waitDialog) {
                            CreateDialog.dismiss(StockApplyProduceActivity.this, waitDialog);
                        }
                        CreateDialog.submitDialog(StockApplyProduceActivity.this, "失败", ApplyDemandHeadDetailItemLiveDataWrapper.error.getMessage(), 101, null, "确定");

                        break;
                }
            }
        });
        viewModel.delete.observe(this, new Observer<ApplyDemandHeadDetailItem>() {
            @Override
            public void onChanged(@Nullable ApplyDemandHeadDetailItem recordResponse) {
                if (null != viewModel.mApplyDemandHeadDetailItems && viewModel.mApplyDemandHeadDetailItems.size() > 0) {
                    viewModel.mApplyDemandHeadDetailItems.remove(recordResponse);
                }
                viewModel.mOtherOutLrAdapter.deleteDate(recordResponse);
            }
        });

        viewModel.edit.observe(this, new Observer<ApplyDemandHeadDetailItem>() {
            @Override
            public void onChanged(@Nullable ApplyDemandHeadDetailItem recordResponse) {
                notifyPosition = recordResponse.getNotifyPosition();
                Intent i = new Intent(StockApplyProduceActivity.this, StockOutHandEditActivity.class);
                i.putExtra("factOut", recordResponse.getNeedNumber());
                i.putExtra("amount", recordResponse.getDemandNumber());
                i.putExtra("canOutNumber", recordResponse.getCanOutNumber());
                i.putExtra("isApply",true);
                startActivityForResult(i, Constants.REQUEST_CODE_EDIT);
            }
        });



        viewModel.getJump().observe(this, new Observer<ApplyDemandHeadDetailItem>() {
            @Override
            public void onChanged(@Nullable ApplyDemandHeadDetailItem response) {
                if(null != response){
                    if(response.isScan()){
                        Intent intent = new Intent(StockApplyProduceActivity.this, StockApplyProduceDetailActivity.class);
                        intent.putExtra("model", response);
                        intent.putExtra("type", Constants.RECEIPTS_CODE_APPLY_FOR);
                        startActivity(intent);
                    }else{
                        Intent intent = new Intent(StockApplyProduceActivity.this, StockOutDetailActivity.class);
                        intent.putExtra("model", response);
                        intent.putExtra("type", Constants.RECEIPTS_CODE_APPLY_FOR);
                        startActivity(intent);
                    }
                }


            }
        });
        viewModel.getPermission().observe(this, new Observer<LiveDataWrapper<StockStorageResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<StockStorageResponse> stockForOtherOutResponseLiveDataWrapper) {
                switch (stockForOtherOutResponseLiveDataWrapper.status) {
                    case LOADING:
                        waitDialog = CreateDialog.waitingDialog(StockApplyProduceActivity.this);
                        break;
                    case SUCCESS:
                        if (null != waitDialog) {
                            CreateDialog.dismiss(StockApplyProduceActivity.this, waitDialog);
                        }
                        if (null != stockForOtherOutResponseLiveDataWrapper.data) {
                            permission = stockForOtherOutResponseLiveDataWrapper.data.getPermission();
                        }
                        break;
                    case ERROR:
                        if (null != waitDialog) {
                            CreateDialog.dismiss(StockApplyProduceActivity.this, waitDialog);
                        }
                       handleException(stockForOtherOutResponseLiveDataWrapper.error, false);
                        break;
                }
            }
        });
        viewModel.pdaSubmit.observe(this, new Observer<LiveDataWrapper<ApplyDemandHeadDetailItem>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<ApplyDemandHeadDetailItem> stringLiveDataWrapper) {
                switch (stringLiveDataWrapper.status) {
                    case LOADING:
                        waitDialog = CreateDialog.waitingDialog(StockApplyProduceActivity.this);
                        break;
                    case SUCCESS:
                        if (null != waitDialog) {
                            CreateDialog.dismiss(StockApplyProduceActivity.this, waitDialog);
                        }
                        break;
                    case ERROR:
                        if (null != waitDialog) {
                            CreateDialog.dismiss(StockApplyProduceActivity.this, waitDialog);
                        }
                        Log.e("PXY", "onChanged: "+ stringLiveDataWrapper.error.getMessage());
                        CreateDialog.submitDialog(StockApplyProduceActivity.this, "提交失败", stringLiveDataWrapper.error.getMessage(), 101, null, "确定");
                  //      handleException(stringLiveDataWrapper.error, false);
                        break;
                }
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            //手动编辑的结果
            case Constants.REQUEST_CODE_EDIT:
                switch (resultCode) {
                    case Constants.RESULT_OK:
                        // 加入到
                        if (null != data) {
                            String count = data.getStringExtra("count");
                            viewModel.mOtherOutLrAdapter.notifyRealStock(notifyPosition, count);
                        }


                        break;
                    case Constants.RESULT_FAIL:

                        break;
                }
                break;
        }

    }
    public void initPop() {
        //实例化SelectPicPopupWindow
        if (null == mMenuPop1) {
            mMenuPop1 = new BottomMenuPopupStock(StockApplyProduceActivity.this, itemsOnClick_OutAdded, permission,"申请出库");
            mMenuPop1.sureOther.setText("仅提交");
            mMenuPop1.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    AlphaManager.backgroundAlpha(1f, StockApplyProduceActivity.this);
                //    mMenuPop1.setVisibility();
                }
            });
        }
        //显示窗口
        mMenuPop1.showAtLocation(StockApplyProduceActivity.this.findViewById(R.id.coordinatorLayout), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
        AlphaManager.backgroundAlpha(0.7f, StockApplyProduceActivity.this);
    }
    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick_OutAdded = new View.OnClickListener() {

        public void onClick(View v) {
            if (null != mMenuPop1 && mMenuPop1.isShowing()) {
                mMenuPop1.dismiss();
            }
            switch (v.getId()) {
                case R.id.sure_submit:
                    viewModel.mApplyDemandHeadDetailItems.get(0).setIsConfirm(permission);
                    viewModel.submit( StockApplyProduceActivity.this);
                    break;
                case R.id.sure_other:
                    viewModel.mApplyDemandHeadDetailItems.get(0).setIsConfirm("n");
                    viewModel.submit(StockApplyProduceActivity.this);
                    break;

                case R.id.only_que:
                    viewModel.mApplyDemandHeadDetailItems.get(0).setIsConfirm("n");
                    viewModel.submit( StockApplyProduceActivity.this);
                    break;
                case R.id.only_cancel:
              //      mMenuPop1.setVisibility();
                    break;
            }
        }
    };
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back:
               onBackPressed();
                break;

            case R.id.tv_submit_other_stock:
                if(null != viewModel.mApplyDemandHeadDetailItems && viewModel.mApplyDemandHeadDetailItems.size()<=0){
                      ToastUtil.toastWarning(StockApplyProduceActivity.this,"空空的物资列表，无法提交",-1);
                      return;
                }
               initPop();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        mDialog = CreateDialog.infoDialog(StockApplyProduceActivity.this, "提醒", "当前出库任务还未提交，是否退出", "否", "是", v12 -> {
            if (null != mDialog) {
                mDialog.cancel();
            }
        }, v1 -> {
            if (null != mDialog) {
                mDialog.cancel();
                setResult(Constants.RESULT_FAIL);
                finish();
            }
        });
    }
    @Override
    protected void onPause() {
        super.onPause();
        closeBroadCast();
    }
    private ThreadManager mThreadManager;
    @Override
    protected void brodcast(Context context, String msg) {
        super.brodcast(context, msg);
        if(null == mThreadManager){
            mThreadManager = new ThreadManager();
        }
        if (msg.contains("code")) {
            if (!isHasFlid){
                mThreadManager.doFolid(binding.appbar.getHeight());
            }
            //mockFliding();
<<<<<<< HEAD
//            String replace = msg.replace("二维码编码", "qrCode");
//            Log.e("PXY", "brodcast: " + replace);
            try {
                JSONObject jsonObject = new JSONObject(msg);
                String qrCode = jsonObject.getString("code");
=======
            String qrCode = msg.substring(msg.indexOf(":") + 1, msg.length());
            Log.e("PXY", "code: "+ qrCode);
>>>>>>> test

                if(ifContain(qrCode)){
                    return;
                }
                viewModel.queryByScan(qrCode);

        } else {
            //不在范围  错误的二维码
             ToastUtil.toastWarning(StockApplyProduceActivity.this, "添加失败,未在系统中找到相关物资信息", -1);
        }

    }
    /**
     * 模拟滑动事件
     */
    private void mockFliding(){
        if (!isHasFlid)
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Instrumentation inst = new Instrumentation();
                    float x = 45.0f;
                    float y = binding.appbar.getHeight();
                    long dowTime = SystemClock.uptimeMillis();
                    inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime,
                            MotionEvent.ACTION_DOWN, x, y,0));
                    inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime,
                            MotionEvent.ACTION_MOVE, x, y - 50,0));
                    inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime+20,
                            MotionEvent.ACTION_MOVE, x, y - 100,0));
                    inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime+30,
                            MotionEvent.ACTION_MOVE, x, y - 150,0));
                    inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime+40,
                            MotionEvent.ACTION_MOVE, x, y - 200,0));
                    inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime+40,
                            MotionEvent.ACTION_UP, x, y - 250,0));
//                    ifFcousFliding = true;
                }
            }).start();

    }
    public boolean ifContain(String qrCode){
        if (null == viewModel.mApplyDemandHeadDetailItems) {
            viewModel.mApplyDemandHeadDetailItems = new ArrayList<>();
            return true;
        }
        if ( viewModel.mApplyDemandHeadDetailItems.size() == 0) {
            //第一次添加
            ToastUtil.toastWarning(StockApplyProduceActivity.this,"当前没有需要扫码的物资",-1);
            return true;
        }
        Set<String> qrCodeSet = new HashSet<>();
        for (ApplyDemandHeadDetailItem s : viewModel.mApplyDemandHeadDetailItems) {
            List<GoodStockRequest> goodStockRequests = s.getqRVOList();
            for(GoodStockRequest request : goodStockRequests){
                if(qrCodeSet.contains(request.getQrCode())){
                    //提示
                    ToastUtil.toastWarning(StockApplyProduceActivity.this, "添加失败,该物资已在本单中添加过了",-1);
                    return true;
                }else{
                    qrCodeSet.add(request.getQrCode());
                }
            }
        }
        if(qrCodeSet.contains(qrCode)){
            //提示
            ToastUtil.toastWarning(StockApplyProduceActivity.this, "添加失败,该物资已在本单中添加过了",-1);
            return true;
        }
        return false;
    }
}
